/*
 * system init
 */

#include "at32f403a_407_board.h"
#include "sys_init.h"
#include "at32_emac.h"
#include "netconf.h"
#include "tcp_client.h"
#include "tcp_server.h"
#include "mqtt_client.h"
#include "os_obj.h"

extern volatile uint32_t local_time;

/*****************************************************************************
 * @brief   fun.
 *****************************************************************************/
void lwip_periodic_common(volatile uint32_t localtime, char netst);
void lwip_periodic_client(volatile uint32_t localtime, char netst);
void lwip_periodic_server(volatile uint32_t localtime, char netst);
void lwip_periodic_mqtt(volatile uint32_t localtime, char netst);

/*****************************************************************************
 * @brief   var.
 *****************************************************************************/
osThreadDef(thd_tcp, task_lwip_tcp, 10, 0, 1024 * 2);
extern struct netif netif;

/*****************************************************************************
 * @brief    task add.
 *
 * @ Pass/ Fail criteria: none
 *****************************************************************************/
static void task_add(void)
{
	osThreadCreate(osThread(thd_tcp), "TCP CLIENT");
}
obj_init_order5(task_add);

/*****************************************************************************
 * @brief   task_lwip_tcp task.
 *
 * @ Pass/ Fail criteria: none
 *****************************************************************************/
void task_lwip_tcp(const void *thread_input)
{
	error_status status;

	at32_board_init();

	delay_init();

	// at32 hal emac init
	status = emac_system_init();

	while (status == ERROR)
		;

	//
	tcpip_stack_init();

	for (;;)
	{
		static uu32 ipold = 0, ipst = 0;

		lwip_periodic_common(local_time, ipst);

		if ((ipold == 0) && (netif.ip_addr.addr != 0))
		{
			ipold = netif.ip_addr.addr;
			dbg_print("LOCAL IP:: %d, %d, %d, %d\n", byte_lb(ipold), byte_hb(ipold), byte_ub(ipold), byte_mb(ipold));

			//tcp_client_init(TCP_CLIENT_LOCAL_PORT, TCP_CLIENT_SERVER_PORT, TCP_CLIENT_SERVER_IP);
			tcp_server_init();
			// mqtt_client_init();

			ipst = 1;
		}

		 //lwip_periodic_client(local_time, ipst);

		lwip_periodic_server(local_time, ipst);

		// lwip_periodic_mqtt(local_time, ipst);

		tx_semaphore_get(os_obj.sid_eth, 1);
	}
}
